<!DOCTYPE html>
<html>

<head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">


    <title>代理管理</title>
    <meta name="keywords" content="">
    <meta name="description" content="">

    <link rel="shortcut icon" href="favicon.ico">
    <link href="../../css/bootstrap.min.css?v=3.3.6" rel="stylesheet">
    <link href="../../css/font-awesome.css?v=4.4.0" rel="stylesheet">
    <link href="../../css/plugins/bootstrap-table/bootstrap-table.min.css" rel="stylesheet">
    <link href="../../css/animate.css" rel="stylesheet">
    <link href="../../css/plugins/ztree/style.css?v=4.1.0" rel="stylesheet">

</head>
<style type="text/css">
    div[class="bars pull-left"]{
        width: 90%;
    }
</style>
<body class="">
<div class="wrapper wrapper-content animated fadeInRight">
	
    <div id="toolbar" class="form-inline">
        <div class="">
            <div class="form-group">
                <input type="text" class="form-control" data-bind="value:phone" placeholder="手机号">
            </div>
            <div class="form-group">
                <input type="text" class="form-control" data-bind="value:agentName"  placeholder="姓名">
            </div>
            <!-- <div class="form-group">
                <label for="startTime">开始时间:</label>
                <input placeholder="开始时间" class="form-control layer-date" id="startTime">
            </div>
            <div class="form-group">
                <label for="endTime">结束时间:</label>
                <input class="form-control layer-date" id="endTime" placeholder="结束时间">
            </div> -->
            <button id="btn_search" type="button" class="btn btn-primary">
                搜索
            </button>
             <button id="btn_reset" type="button" class="btn btn-primary">
                重置
            </button> 
           <!-- <button id="btn_add" type="button" class="btn btn-default">
                <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
            </button>-->
        </div>
    </div>

    <table id="tb_dept" >
        <thead>
            <tr>
                <th data-checkbox="true"></th>
                <!-- <th data-field="agentName">姓名</th>
                <th data-field="phone">手机号</th>
                <th data-field="idNum" >身份证号</th>
                <th data-field="recommendName">上级代理</th>
                <th data-field="amount" data-formatter="amountFormatter">账户余额</th>
                <th data-field="addTime">创建时间</th>
                <th data-field="operate" data-formatter="operateFormatter">操作</th> -->
                <th data-field="name">姓名</th>
                <th data-field="mobile">手机号</th>
                <th data-field="balance" data-formatter="amountFormatter">账户余额</th>
                <th data-field="addTime">注册时间</th>
                <th data-field="operate" data-formatter="operateFormatter">操作</th>
            </tr>
        </thead>
    </table>

</div>
</body>
<!-- 全局js -->
<script src="../../js/jquery.min.js?v=2.1.4"></script>
<script src="../../js/bootstrap.min.js?v=3.3.6"></script>

<!-- 自定义js -->
<script src="../../js/content.js?v=1.0.0"></script>


<!-- Bootstrap table -->
<script src="../../js/plugins/bootstrap-table/bootstrap-table.min.js"></script>
<script src="../../js/plugins/bootstrap-table/bootstrap-table-mobile.min.js"></script>
<script src="../../js/plugins/bootstrap-table/locale/bootstrap-table-zh-CN.min.js"></script>
<!--MVVM框架-->
<script type="text/javascript" src="../../js/plugins/knockout/knockout-3.4.2.js"></script>
<script type="text/javascript" src="../../js/plugins/knockout/knockout.mapping-latest.js"></script>

<!-- layerDate plugin javascript -->
<script type="text/javascript" src="../../js/plugins/layer/laydate/laydate.js"></script>
<script type="text/javascript" src="../../js/common/auth.js"></script>
<script id="addTpl" type="text/html" >
    <div class="form-horizontal"style="overflow: hidden;margin-top: 20px">
        <div class="form-group">
            <label for="agentName" class="col-sm-3 control-label">姓名</label>
            <div class="col-sm-8">
                <input type="text" class="form-control" data-bind='value:agentName'  id="agentName" placeholder="请输入姓名">
            </div>
            <span class="req" style=" display: inline-block;margin-top: 6px;color: red;font-size: 20px;">*</span>
        </div>
        <div class="form-group">
            <label for="phone" class="col-sm-3 control-label">手机号</label>
            <div class="col-sm-8">
                <input type="text" class="form-control" data-bind='value:phone' id="phone" placeholder="请输入手机号">
            </div>
            <span class="req" style=" display: inline-block;margin-top: 6px;color: red;font-size: 20px;">*</span>
        </div>
        <div class="form-group">
            <label for="idNum" class="col-sm-3 control-label">身份证号</label>
            <div class="col-sm-8">
                <input  class="form-control" data-bind='value:idNum' id="idNum" placeholder="请输入身份证号">
            </div>
            <span class="req" style=" display: inline-block;margin-top: 6px;color: red;font-size: 20px;">*</span>
        </div>
        <!-- <div class="form-group">
            <label for="search" class="col-sm-3 control-label">上级代理</label>
            <div class="col-sm-8">
            	<input type="text"  class="form-control"  id="search" placeholder="请输入上级代理关键字">
                <input type="hidden" class="form-control" data-bind='value:recommendId' id="recommendId" >
            </div> -->
        </div>
        <div class="form-group">
            <label for="mark" class="col-sm-3 control-label">备注</label>
            <div class="col-sm-8">
                <input  class="form-control" data-bind='value:mark' id="mark" placeholder="请输入备注">
            </div>
        </div>
        <div class="form-group">
            <label for="status" class="col-sm-3 control-label">状态</label>
            <div class="col-sm-8">
	            <select data-bind="value:status" id="status" class="col-sm-5 control-label">
	        		<option value="" style="color:green;">请选择</option>
	            	<option value="0" style="color:green;">未删除</option>
	                <option value="1" style="color:green;">删除</option>
	        	</select>
	        </div>
	        <span class="req" style=" display: inline-block;margin-top: 6px;color: red;font-size: 20px;">*</span>
        </div>
        <div class="form-group">
            <label for="userType" class="col-sm-3 control-label">代理类型</label>
            <div class="col-sm-8">
	            <select data-bind="value:userType" id="userType" class="col-sm-5 control-label">
	        		<option value="" style="color:green;">请选择</option>
	            	<option value="1" style="color:green;">代理</option>
	                <option value="2" style="color:green;">讲师管理</option>
	        	</select>
	        </div>
	        <span class="req" style=" display: inline-block;margin-top: 6px;color: red;font-size: 20px;">*</span>
        </div>
    </div>    
</script>

<script id="updateTpl" type="text/html" >
    <div class="form-horizontal"style="overflow: hidden;margin-top: 20px">
        <div class="form-group">
            <label for="agentName" class="col-sm-3 control-label">姓名</label>
            <div class="col-sm-8">
                <input type="text" class="form-control" data-bind='value:agentName'  id="agentName" placeholder="请输入姓名">
            </div>
            <span class="req" style=" display: inline-block;margin-top: 6px;color: red;font-size: 20px;">*</span>
        </div>
        <div class="form-group">
            <label for="phone" class="col-sm-3 control-label">手机号</label>
            <div class="col-sm-8">
                <input type="text" class="form-control" data-bind='value:phone' id="phone" placeholder="请输入手机号">
            </div>
            <span class="req" style=" display: inline-block;margin-top: 6px;color: red;font-size: 20px;">*</span>
        </div>
        <div class="form-group">
            <label for="idNum" class="col-sm-3 control-label">身份证号</label>
            <div class="col-sm-8">
                <input  class="form-control" data-bind='value:idNum' id="idNum" placeholder="请输入身份证号">
            </div>
            <span class="req" style=" display: inline-block;margin-top: 6px;color: red;font-size: 20px;">*</span>
        </div>
        <div class="form-group">
            <label for="search" class="col-sm-3 control-label">上级代理</label>
            <div class="col-sm-8">
            	<input type="text"  class="form-control"  id="search" placeholder="请输入上级代理关键字">
                <input type="hidden" class="form-control" data-bind='value:recommendId' id="recommendId" >
            </div>
        </div>
        <div class="form-group">
            <label for="mark" class="col-sm-3 control-label">备注</label>
            <div class="col-sm-8">
                <input  class="form-control" data-bind='value:mark' id="mark" placeholder="请输入备注">
            </div>
        </div>
        <div class="form-group">
            <label for="status" class="col-sm-3 control-label">状态</label>
            <div class="col-sm-8">
	            <select data-bind="value:status" id="status" class="col-sm-5 control-label">
	        		<option value="" style="color:green;">请选择</option>
	            	<option value="0" style="color:green;">未删除</option>
	                <option value="1" style="color:green;">删除</option>
	        	</select>
	        </div>
	        <span class="req" style=" display: inline-block;margin-top: 6px;color: red;font-size: 20px;">*</span>
        </div>
        <div class="form-group">
            <label for="userType" class="col-sm-3 control-label">代理类型</label>
            <div class="col-sm-8">
	            <select data-bind="value:userType" id="userType" class="col-sm-5 control-label">
	        		<option value="" style="color:green;">请选择</option>
	            	<option value="1" style="color:green;">代理</option>
	                <option value="2" style="color:green;">讲师管理</option>
	        	</select>
	        </div>
	        <span class="req" style=" display: inline-block;margin-top: 6px;color: red;font-size: 20px;">*</span>
        </div>
    </div>        
</script>


<script type="text/javascript">
    var __addOrUpdateUrl = "/appAgent";//post 更新或添加
    var __listUrl = "/appAgent/lecturerGroup";  //put 获取列表
    var __delUrl = "/appAgent"; //delete 方式 删除
    var maxHeight = top.document.body.clientHeight * 0.8 ; //文档高度的80%
    //初始化
    $(function () {
        //1、初始化表格
        tableInit.Init();

        //2、注册增删改事件
        operate.operateInit();

        //3、日期初始化
        dateInit.Init();

        
    });

    var koModel={
        searchModel:{
        	phone:ko.observable(),
            agentName:ko.observable()
        }
    };

    function GetRequest() {
  var url = location.search; //获取url中"?"符后的字串
   var theRequest = new Object();
   if (url.indexOf("?") != -1) {
      var str = url.substr(1);
      strs = str.split("&");
      for(var i = 0; i < strs.length; i ++) {
         theRequest[strs[i].split("=")[0]]=(strs[i].split("=")[1]);
      }
   }
   return theRequest;
    }
    //初始化表格
    var tableInit = {
        Init: function () {
            function queryParams(param){
                var unmapped = ko.mapping.toJS(koModel.searchModel);
                var pa = { pageSize: param.limit, pageNum : param.offset/param.limit+1 }
                if($("#startTime").val()){
                    pa.startTime = $("#startTime").val();
                }
                if($("#endTime").val()){
                    pa.endTime = $("#endTime").val();
                }
                pa.orderBy = "add_time";
                var Request = new Object();
                Request = GetRequest();
              
                var id = Request['id'];
                pa.fkManageId = id;
               
                //return JSON.stringify($.extend(pa,unmapped));
                return $.extend(pa,unmapped);
            }

            $("#tb_dept").bootstrapTable({
                url: __listUrl,
                method: 'post',   //请求方式（*）
                contentType:'application/json',      //数据格式          
                toolbar: '#toolbar',                //工具按钮用哪个容器
                queryParams: queryParams, 
                pagination: true,                   //是否显示分页（*）
                sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
                paginationHAlign:"right",
                uniqueId:"id",
                pageNumber: 1,                      //初始化加载第一页，默认第一页
                pageSize: 10,                       //每页的记录行数（*）
                pageList: [10, 25, 50, 100],       //可供选择的每页的行数（*）
                search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
                strictSearch: true,
                showColumns: true,                  //是否显示所有的列
                cache:false,
                showRefresh: true,                  //是否显示刷新按钮
                minimumCountColumns: 2,             //最少允许的列数
                clickToSelect: true,                //是否启用点击选中行
                showToggle: false,
                responseHandler:function(res){
                    if(res.code==401){
                        top.window.location.href=top.window.location.origin+"/login.html";
                    }
                    if(res.code!=200){
                       alert(res.msg);
                    }
                    return {
                       
                        "total":res.data.totalCount,
                        "rows":res.data.rows
                    }
                }
            });
        }
    };

    /**
     每行的操作按钮
     */
    function operateFormatter(value, row, index){
       // var html = "";
    
    	var  html  = '<button  type="button" class="btn btn-default" onclick="operate.operateCourse(\''+row.id+'\')">录播课程</button>&nbsp;&nbsp;<button  type="button" class="btn btn-default" onclick="operate.operateLive(\''+row.id+'\')">直播课程</button>';
        return html;
    }
    
    function typeFormatter(value, row, index){
    	if(value&&value==1){
    		return "代理";
    	}else{
    		return "讲师专家"
    	}
    }
    
    function amountFormatter(value, row, index){
    	if(value){
    		return value/100;
    	}	
    }

	function getTable(){
		return $("#tb_dept");
	}
    function getSelections(){
        return getTable().bootstrapTable('getSelections');
    }
    function refreshTable(){
        getTable().bootstrapTable("refresh");
    }
    
    //操作
    var operate = {
        //初始化按钮事件
        operateInit: function () {
            this.operateAdd();
            //this.operateUpdate();
            //this.operateDelete();
            this.operateSearch();//搜索清空按钮绑定初始化
            this.entityModel ={
                phone: ko.observable(),
                agentName: ko.observable(),
                idNum: ko.observable(),
                recommendId: ko.observable(),
                mark: ko.observable(),
                status: ko.observable(),
                userType: ko.observable(),
                amount: ko.observable()
            };
        },
        //新增
        operateAdd: function(){
            $('#btn_add').on("click", function () {
                var newModel =   operate.entityModel;
                top.layer.open({
                    title:"代理人新增",
                    type: 1,
                    area: "500px",
                    maxHeight:maxHeight,
                    content:$("#addTpl").html(),
                    btn: ["保存", "取消"],
                    yes: function(index, layerDom){
                    	var close = top.layer.load(1);
		                var unmapped = ko.mapping.toJS(newModel);
                        unmapped.amount = unmapped.amount * 100;
                        if(!operate.operateCheck(unmapped)){
                        	top.layer.close(close);
                            return;
                        }
                        $$ajax({
                            url: __addOrUpdateUrl,
                            type: 'post',//提交的方式
                            dataType:'json',
                            contentType:"application/json; charset=utf-8",
                            data:JSON.stringify(unmapped),
                            success: function(data) {
                                console.log(data.msg)
                                if (data.httpCode==200) {
                                	top.layer.close(close);
                                	refreshTable();
                                	top.layer.alert("添加成功")
                                	top.layer.close(index);
                                } else{
                                	top.layer.close(close);
                                    alert(data.msg);
                                }
                            }
                        });
                    },
                    btn2:function(index,layarDom){//关闭
                        ko.cleanNode(layarDom.get(0));
                    },
                    success:function(layarDom,index){//弹层加载成功
                    	
                    	function formatAgentParams(param) {
                            return JSON.stringify({ pageNum: 1, pageSize: 10, agentName: param.agentName });
                        }
                        
                        //添加邀请人自动提示
                        top.$("#search", top.$(layarDom)).autocomplete({
                            serviceUrl: __listUrl,
                            type: "put",
                            paramName: "agentName",
                            queryParam: formatAgentParams,
                            zIndex:268000000,
                            ajaxSettings: {
                                contentType: "application/json; charset=utf-8",
                                dataType: "JSON"
                            },
                            transformResult: function (response) {
                                console.log(response.data )
                                var bbs = {
                                    suggestions: top.$.map(response.data, function(dataItem) {
                                        return { value: dataItem.agentName,id:dataItem.id};
                                    })
                                };
                                return bbs; 
                            },
                            onSelect: function (suggestion) {
                                console.log(suggestion)
                                newModel.recommendId(suggestion.id);
                            }
                        });
                    	
                        ko.applyBindings(newModel, layarDom.get(0));
                    }
                });
            });
        },
        //编辑修改
        operateCourse: function (id) {
            var row = getTable().bootstrapTable("getRowByUniqueId",id);
            row.amount = row.amount/100;
            var newModel = ko.mapping.fromJS(row);
            //window.location.href = './coursesList.html?id='+id;
            top.layer.open({
                title:"课程列表",
                type: 2,
                area: ["1000px","650px"],
                maxHeight:maxHeight,
                content:"/html/app_expert/coursesList.html?id="+id,
               // btn: [ "返回"],
                yes: function(index, layerDom){
                	var close = top.layer.load(1);
                	var value = row.phone;
					var change = $("#phone",$(layerDom)).val();
					var arr = [];
					if(change!=value){
						$$ajax({
							url: __listUrl,
							type: 'put',//提交的方式
							dataType:'json',
							async:false,
							contentType:"application/json; charset=utf-8",
							data:JSON.stringify({phone:change}),
							success: function(response) {
								console.log(response.msg)
								if (response.httpCode==200) {
									arr = response.data;
								} else{
									alert(data.msg);
								}
							}
						});
					}
					if(arr.length>0){
						alert("此手机号已被注册！");
						top.layer.close(close);
						return ;
					}
					var jsModle = ko.mapping.toJS(newModel);
					jsModle.amount = jsModle.amount * 100;
					if(!operate.operateCheck(jsModle)){
						top.layer.close(close);
						return;
					}
					$$ajax({
						url: __addOrUpdateUrl,
						type: 'post',//提交的方式
						dataType:'json',
						contentType:"application/json; charset=utf-8",
						data:JSON.stringify(jsModle),
						success: function(data) {
							console.log(data.msg)
							if (data.httpCode==200) {
								top.layer.close(close);
								top.layer.alert("更新成功",{icon:6});
								top.layer.close(index);
								refreshTable();
							} else{
								top.layer.close(close);
								alert(data.msg);
							}
						}
					});
               },
             btn2:function(index,layarDom){//关闭
                   ko.cleanNode(layarDom.get(0));
               },
                success:function(layarDom,index){//弹层加载成功
                	$("#search",$(layarDom)).val(row.recommendName);
                	ko.applyBindings(newModel,layarDom.get(0));
                }
            });

        },
        operateLive: function (id) {
            var row = getTable().bootstrapTable("getRowByUniqueId",id);
            row.amount = row.amount/100;
            var newModel = ko.mapping.fromJS(row);
            top.layer.open({
                title:"直播列表",
                type: 2,
                area: ["1000px","650px"],
                maxHeight:maxHeight,
                content:"/html/app_expert/liveList.html?id="+id,
              //  btn: [ "返回"],
                yes: function(index, layerDom){
                	var close = top.layer.load(1);
                	var value = row.phone;
					var change = $("#phone",$(layerDom)).val();
					var arr = [];
					if(change!=value){
						$$ajax({
							url: __listUrl,
							type: 'put',//提交的方式
							dataType:'json',
							async:false,
							contentType:"application/json; charset=utf-8",
							data:JSON.stringify({phone:change}),
							success: function(response) {
								console.log(response.msg)
								if (response.httpCode==200) {
									arr = response.data;
								} else{
									alert(data.msg);
								}
							}
						});
					}
					if(arr.length>0){
						alert("此手机号已被注册！");
						top.layer.close(close);
						return ;
					}
					var jsModle = ko.mapping.toJS(newModel);
					jsModle.amount = jsModle.amount * 100;
					if(!operate.operateCheck(jsModle)){
						top.layer.close(close);
						return;
					}
					$$ajax({
						url: __addOrUpdateUrl,
						type: 'post',//提交的方式
						dataType:'json',
						contentType:"application/json; charset=utf-8",
						data:JSON.stringify(jsModle),
						success: function(data) {
							console.log(data.msg)
							if (data.httpCode==200) {
								top.layer.close(close);
								top.layer.alert("更新成功",{icon:6});
								top.layer.close(index);
								refreshTable();
							} else{
								top.layer.close(close);
								alert(data.msg);
							}
						}
					});
               },
             btn2:function(index,layarDom){//关闭
                   ko.cleanNode(layarDom.get(0));
               },
                success:function(layarDom,index){//弹层加载成功
                	$("#search",$(layarDom)).val(row.recommendName);
                	ko.applyBindings(newModel,layarDom.get(0));
                }
            });

        },

        //单条删除(假删：把状态改为删除)
        operateDelete: function (id) {
        	if(confirm("确认删除？")){
        		var close = top.layer.load(1);
		  		$$ajax({
                    url: __addOrUpdateUrl,
                    type: 'post',//提交的方式
                    dataType:'json',
                    contentType:"application/json; charset=utf-8",
                    data:JSON.stringify({id:id,status:1}),
                    success: function(data) {
                        console.log(data.msg)
                        if (data.httpCode==200) {
                        	top.layer.close(close);
                        	top.layer.close(index);
                            top.layer.alert("删除成功",{icon:6});
                            refreshTable();
                        } else{
                        	top.layer.close(close);
                            alert(data.msg);
                        }
                    }
                });
        	}
        },
        
        //搜索清空绑定
        operateSearch:function(){
            //ko模型绑定
            ko.applyBindings(koModel.searchModel, $("#toolbar").get(0));
            $("#btn_search").click(function(event) {
                var searchObj = ko.mapping.toJS(koModel.searchModel);
                $("#tb_dept").bootstrapTable("refreshOptions",{pageNumber:1});
                refreshTable();
            });
            $("#btn_reset").click(function(event) {
                $("#startTime").val("");
                $("#endTime").val("");
                koModel.searchModel.agentName("");
                koModel.searchModel.phone("");
            });
        },
        //数据校验
        operateCheck:function(entity){
        	var regexp = "^[0-9]+(.[0-9]{1,2})?$";
            var reg = "(^[0-9]{15}$)|(^[0-9]{18}$)|(^[0-9]{17}([0-9]|X|x)$)";
            if (!entity.agentName) {
                alert("姓名不能为空，请填写姓名!");
                return false;
            }
            if (!entity.status) {
                alert("状态不能为空，请选择!");
                return false;
            }
            if (!entity.userType) {
                alert("类型不能为空，请选择!");
                return false;
            }
            if (!entity.phone.match(regexp)) {
                alert("手机号只能为数字!");
                return false;
            }
            if (entity.phone.length!=11) {
                alert("手机号为11位!");
                return false;
            }
            if(!entity.idNum){
            	alert("身份证号不能为空!");
                return false;
            }
	        if (!entity.idNum.match(reg)) {
                alert("身份证格式有误!");
                return false;
            }
            return true;
        }
    }
    
    
	
	
    var dateInit ={
        Init:function(){
            var that = this;
            //日期范围限制
            this.start = {
                elem: '#startTime',
                format: 'yyyy-MM-dd HH:mm:ss',
                min: '1971-01-01 00:00:00', //设定最小日期为当前日期
                max: '2099-06-16 23:59:59', //最大日期
                istime: true,
                istoday: false,
                choose: function (datas) {
                    //that.end.min = datas; //开始日选好后，重置结束日的最小日期
                    //that.end.start = datas //将结束日的初始值设定为开始日
                }
            };
            this.end = {
                elem: '#endTime',
                format: 'yyyy-MM-dd HH:mm:ss',
                min: '1971-01-01 00:00:00',
                max: '2099-06-16 23:59:59',
                istime: true,
                istoday: false,
                choose: function (datas) {
                    //that.start.max = datas; //结束日选好后，重置开始日的最大日期
                }
            };
           
            laydate.render(this.start);
            laydate.render(this.end);
            
        },
        customInitLayDate:function (elem){
        	return {
                elem: elem,
                format: 'yyyy-MM-dd HH:mm:ss',
                min: '1971-01-01 00:00:00', //设定最小日期为当前日期
                max: '2099-06-16 23:59:59', //最大日期
                istime: true,
                istoday: false,
                choose: function (datas) {
                    //that.end.min = datas; //开始日选好后，重置结束日的最小日期
                    //that.end.start = datas //将结束日的初始值设定为开始日
                }
            }
        }
    }
	
</script>

</html>